import React, { useEffect, useState } from 'react';
import { Button, message, Form, Input, Modal, Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import request from '../../../libs/request';
const IPaddress = ({ setCurrent }) => {

  const [form] = Form.useForm();

  let obj = null

  const [isModalOpen, setIsModalOpen] = useState(false);
  useEffect(() => {
    request("/api/gslock/readip").then(res => {
      if (res.code != 0) return message.error(res.msg)
      obj = {
        ip: res.ip,
        mask: res.mask,
        gateway: res.gateway,
        dns: res.dns
      }
      form.setFieldsValue({
        ip: res.ip,
        mask: res.mask,
        gateway: res.gateway,
        dns: res.dns
      })
    })
    // 
  }, [])



  const onFinish = values => {

    let res = isEqual(values, obj)

    if (res) return ok(1)

    obj = {
      ip: values.ip.trim().replace(/\s+/g, ''),
      mask: values.mask.trim().replace(/\s+/g, ''),
      gateway: values.gateway.trim().replace(/\s+/g, ''),
      dns: values.dns.trim().replace(/\s+/g, '')
    }
    request.post("/api/gslock/setip", { ...obj }).then(res => {
      console.log(res)
      if (res.code == -1) return message.error(res.msg)

      ok(2)
    })

  };

  const ok = (flag) => {


    request.post("/api/v1/locker/sys-installs", {
      "install_key": "set_ip",
      "install_step": 2,
      "install_ip": form.getFieldValue("ip").trim().replace(/\s+/g, ''),
      "install_ip_config": JSON.stringify(obj)
    }).then(res => {
      console.log(res)
      if (flag === 1) return setCurrent(2)
      setIsModalOpen(true)

    })
  }
  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);

  };


  function isEqual(a, b) {
    const keysA = Object.keys(a);
    return (
      keysA.length === Object.keys(b).length &&
      keysA.every(k => a[k] === b[k])
    );
  }
  return (
    <>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        form={form}
      >

        <Form.Item
          label="IP地址"
          name="ip"
          rules={[{ required: true, message: '请输入IP地址!' }]}
        >
          <Input placeholder='请输入IP地址' />
        </Form.Item>

        <Form.Item
          label="子网掩码"
          name="mask"
          rules={[{ required: true, message: '请输入子网掩码!' }]}
        >
          <Input placeholder='请输入子网掩码' />
        </Form.Item>


        <Form.Item
          label="网关ip"
          name="gateway"
          rules={[{ required: true, message: '请输入网关ip!' }]}
        >
          <Input placeholder='请输入网关ip' />
        </Form.Item>

        <Form.Item
          label="DNS地址"
          name="dns"
          rules={[{ required: true, message: '请输入DNS地址!' }]}
        >
          <Input placeholder='请输入DNS地址' />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
      <Model isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen}  ip={'http://' + form.getFieldValue("ip") + "/login"} />
    </>
  )
}

const Model = ({ isModalOpen, setIsModalOpen, ip }) => {
  const [time, setTime] = useState(20);   // 直接存秒数，方便模板

  useEffect(() => {
    if (!isModalOpen) return;             // 弹窗关着就不跑

    const timer = setInterval(() => {
      setTime(t => {
        if (t <= 1) {                     // 减到 0 时清场
          clearInterval(timer);
          setIsModalOpen(false);
          window.location.replace(ip)
          return 0;
        }
        return t - 1;
      });
    }, 1000);

    return () => clearInterval(timer);    // 组件卸载或弹窗关闭时清理
  }, [isModalOpen, setIsModalOpen]);

  // 弹窗打开时重置倒计时
  useEffect(() => {
    if (isModalOpen) setTime(20);
  }, [isModalOpen]);

  return (
    <Modal
      title="设置成功 请稍等"
      visible={isModalOpen}
      footer={null}
      maskClosable={false}
      closable={false}
    >
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8 }}>
        <Spin indicator={<LoadingOutlined spin />} size="large" />
        <div>正在跳转新的 IP 地址，请稍后 {time} 秒</div>
      </div>
    </Modal>
  );
}

export default IPaddress;